package org.example.day06;

import java.util.concurrent.atomic.AtomicLong;

/**
 *  第二章节:2.3.2.5: 使用原子类可以使addAndGet()方法是原子的，但是该方法的调用顺序是无序的。
 */
public class MyThread9 {
    public static AtomicLong ai = new AtomicLong();
    //如果不加synchronized修饰，则addAndGet()是可以保证原子性的，但是addNum()方法的调用是不能保证原子性的。
    synchronized public void addNum(){
        System.out.println(Thread.currentThread().getName() + " 加了100之后的值是: " + ai.addAndGet(100));
        ai.addAndGet(1);
    }

    public static void main(String[] args) {
        try {
            MyThread9 m9 = new MyThread9();
            Thread9A[] array = new Thread9A[5];
            for (int i = 0; i < array.length; i++) {
                array[i] = new Thread9A(m9);
            }
            for (int i = 0; i < array.length; i++) {
                array[i].start();
            }
            Thread.sleep(1000);
            System.out.println(m9.ai.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread9A extends Thread{
    private MyThread9 m9;

    public Thread9A(MyThread9 m9) {
        this.m9 = m9;
    }

    @Override
    public void run() {
        m9.addNum();
    }
}